#!/usr/bin/env python3
"""
最简单的修复脚本，直接操作数据库
"""

import os
import sys
import uuid
from datetime import datetime

# 确保使用正确的路径
api_dir = os.path.join(os.path.dirname(__file__), 'api')
sys.path.insert(0, api_dir)

from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from app.models import Base, User, App, Memory, MemoryAccessLog

# 创建数据库连接
DATABASE_URL = "sqlite:///./openmemory.db"
engine = create_engine(DATABASE_URL, connect_args={"check_same_thread": False})
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)

# 创建表
print("🚀 初始化数据库...")
Base.metadata.create_all(bind=engine)

# 创建会话
db = SessionLocal()

try:
    # 创建默认用户
    user = db.query(User).filter(User.user_id == "default_user").first()
    if not user:
        user = User(
            id=uuid.uuid4(),
            user_id="default_user",
            name="Default User",
            created_at=datetime.now()
        )
        db.add(user)
        db.commit()
        print("✅ 创建默认用户")
    else:
        print("ℹ️  默认用户已存在")

    # 检查所有应用
    apps = db.query(App).filter(App.owner_id == user.id).all()
    
    print(f"\n📋 找到 {len(apps)} 个应用:")
    for app in apps:
        memory_count = db.query(Memory).filter(Memory.app_id == app.id).count()
        print(f"   - {app.name} (ID: {app.id}, 记忆: {memory_count})")
    
    # 查找OpenMemory相关应用
    openmemory_apps = [app for app in apps if "openmemory" in app.name.lower()]
    
    if len(openmemory_apps) > 1:
        print(f"\n🔍 发现 {len(openmemory_apps)} 个OpenMemory相关应用，需要合并")
        
        # 保留第一个，合并其他的
        keep_app = openmemory_apps[0]
        merge_apps = openmemory_apps[1:]
        
        print(f"📌 保留: {keep_app.name} ({keep_app.id})")
        print(f"📤 合并: {[f'{app.name} ({app.id})' for app in merge_apps]}")
        
        # 标准化名称
        keep_app.name = "OpenMemory"
        
        total_memories = 0
        total_logs = 0
        
        for merge_app in merge_apps:
            # 合并记忆
            memories = db.query(Memory).filter(Memory.app_id == merge_app.id).all()
            for memory in memories:
                memory.app_id = keep_app.id
                total_memories += 1
            
            # 合并访问日志
            logs = db.query(MemoryAccessLog).filter(MemoryAccessLog.app_id == merge_app.id).all()
            for log in logs:
                log.app_id = keep_app.id
                total_logs += 1
            
            # 删除合并的应用
            db.delete(merge_app)
        
        db.commit()
        
        print(f"✅ 合并完成！")
        print(f"   保留应用: {keep_app.name} ({keep_app.id})")
        print(f"   合并记忆: {total_memories} 条")
        print(f"   合并日志: {total_logs} 条")
        
    elif len(openmemory_apps) == 1:
        app = openmemory_apps[0]
        print(f"✅ 已有一个OpenMemory应用: {app.name} ({app.id})")
        
        # 标准化名称
        if app.name != "OpenMemory":
            app.name = "OpenMemory"
            db.commit()
            print("📝 标准化应用名称为 'OpenMemory'")
            
    else:
        print("ℹ️  没有找到OpenMemory应用，创建一个")
        
        app = App(
            id=uuid.uuid4(),
            name="OpenMemory",
            owner_id=user.id,
            created_at=datetime.now(),
            updated_at=datetime.now()
        )
        db.add(app)
        db.commit()
        print("✅ 创建OpenMemory应用")
    
    # 最终确认
    final_apps = db.query(App).filter(App.owner_id == user.id).all()
    print(f"\n📊 最终应用列表:")
    for app in final_apps:
        memory_count = db.query(Memory).filter(Memory.app_id == app.id).count()
        print(f"   - {app.name} (ID: {app.id}, 记忆: {memory_count})")

finally:
    db.close()

print("\n🎉 修复完成！")